package com.example.mymvvmdemo.base;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewbinding.ViewBinding;

import com.example.mymvvmdemo.R;
import com.example.mymvvmdemo.dialog.LoadingAnimDialog;
import com.example.mymvvmdemo.utils.LogUtils;
import com.example.mymvvmdemo.utils.MyActivityUtils;
import com.example.mymvvmdemo.utils.NotchScreenUtil;
import com.example.mymvvmdemo.utils.StrUtils;
import com.example.mymvvmdemo.utils.ToastUtils;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class BaseLoadFragment<VB extends ViewBinding> extends Fragment {

    protected VB binding;

    /*** View */
    private View mRootView;
    /*** 上下文 */
    public Activity mActivity;
    /*** 加载时候的Dialog */
    private LoadingAnimDialog loadingDialog;
    public Gson gson;
    //是否有状态栏
    private boolean hasNavigationBar;
    //状态栏高度
    public int statusBarHeight;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        LogUtils.d("zxh", "mRootView = " + mRootView + "   binding = " + binding);
        mActivity = getActivity();
        if (mRootView == null) {
            mRootView = initVB();
        }
        ViewGroup parent = (ViewGroup) mRootView.getParent();
        if (parent != null) {
            parent.removeView(mRootView);
        }
        LogUtils.d("zxh", "mRootView = " + mRootView + "   parent = " + parent + "   binding = " + binding);
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        gson = new Gson();
        initData();
        hasNavigationBar = ImmersionBar.hasNavigationBar(this);
        if (hasNavigationBar) {
            statusBarHeight = NotchScreenUtil.getNotchSize(getContext())[1];
        }
        initDialog();
        initListener();
        initStatusBar();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        destroyDialog();
    }

    /**
     * 获得视图
     *
     * @return
     */
    private View initVB() {
        Type superclass = getClass().getGenericSuperclass();
        Class<?> aClass = (Class<?>) ((ParameterizedType) superclass).getActualTypeArguments()[0];
        try {
            Method method = aClass.getDeclaredMethod("inflate", LayoutInflater.class);
            binding = (VB) method.invoke(null, getLayoutInflater());
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            LogUtils.e(e.getMessage());
        }
        return binding.getRoot();
    }

    /**
     * 修改dialog文案
     */
    public void setDialogText(String text) {
        if (!this.isAdded()) {
            return;
        }
        if (loadingDialog == null)
            loadingDialog = new LoadingAnimDialog(mActivity, getResources().getString(R.string.load));
        loadingDialog.setText(text);
    }

    /**
     * 统一显示dialog，如果想实现其他样式重写此方法即可
     */
    public void showDialog() {
        if (!this.isAdded()) {
            return;
        }
        if (loadingDialog == null)
            loadingDialog = new LoadingAnimDialog(mActivity, getResources().getString(R.string.load));
        if (!loadingDialog.isShowing()) loadingDialog.show(getActivity());
    }

    /**
     * 隐藏dialog
     */
    public void dismissDialog() {
        if (!this.isAdded()) {
            return;
        }
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.close(getActivity());
        }
    }

    /**
     * 隐藏dialog
     */
    public void dismissDialog(boolean isRun) {
        if (!this.isAdded()) {
            return;
        }
        if (isRun) {
            if (!MyActivityUtils.isForeground(getActivity())) {
                return;
            }
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (loadingDialog != null && loadingDialog.isShowing()) {
                        loadingDialog.close(getActivity());
                    }
                }
            });
        } else {
            if (loadingDialog != null && loadingDialog.isShowing()) {
                loadingDialog.close(getActivity());
            }
        }
    }

    /**
     * 隐藏dialog
     */
    public void destroyDialog() {
        if (loadingDialog != null) {
            loadingDialog.destroyDialog();
        }
    }

    public void initDialog() {

    }

    //适配状态栏
    public void initStatusBar() {

    }

    protected abstract void initData();

    protected abstract void initListener();


    public void toast(String message, int type) {
        try {
            if (!StrUtils.isEmpty(message))
                ToastUtils.getToastUtils().toast(message, type);
        } catch (Exception e) {
        }
    }

    public void toast(int resId, int type) {
        try {
            String message = getString(resId);
            if (!StrUtils.isEmpty(message))
                ToastUtils.getToastUtils().toast(getContext(), resId, type);
        } catch (Exception e) {
        }
    }

    public void toast(String message, boolean isRun, int type) {
        if (isRun) {
            if (!MyActivityUtils.isForeground(getActivity())) {
                return;
            }
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (!StrUtils.isEmpty(message))
                            ToastUtils.getToastUtils().toast(message, type);
                    } catch (Exception e) {
                    }
                }
            });
        } else {
            try {
                if (!StrUtils.isEmpty(message))
                    ToastUtils.getToastUtils().toast(message, type);
            } catch (Exception e) {
            }
        }

    }

    public void toast(int resId, boolean isRun, int type) {
        if (isRun) {
            if (!MyActivityUtils.isForeground(getActivity())) {
                return;
            }
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        String message = getString(resId);
                        if (!StrUtils.isEmpty(message))
                            ToastUtils.getToastUtils().toast(getContext(), resId, type);
                    } catch (Exception e) {
                    }
                }
            });
        } else {
            try {
                String message = getString(resId);
                if (!StrUtils.isEmpty(message))
                    ToastUtils.getToastUtils().toast(getContext(), resId, type);
            } catch (Exception e) {
            }
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    /**
     * 得到屏幕宽度
     */
    public int getScreenWidth() {
        WindowManager windowManager = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    }

    /**
     * 得到屏幕高度
     */
    public int getScreenHeight() {
        WindowManager windowManager = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.heightPixels;
    }

    /**
     * 判断是否是竖屏状态
     *
     * @return
     */
    public boolean isLongitudinal() {
        //TODO 这里遇到一个问题，高版本三星手机获取的横竖屏状态有误，为解决这个问题，根据屏幕宽高判断横竖屏
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        int widthPixels = dm.widthPixels;
        int heightPixels = dm.heightPixels;
        if (heightPixels > widthPixels)
            return true;
        else if (heightPixels < widthPixels)
            return false;

        return getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    }

//    public String getLanguage() {
//        String language = SpUtils.getSpUtils(MyApplication.getInstance(), Constants.ACCOUNT_NAME)
//                .getStringValue(Constants.USER_LANGUAGE_HEAD, null);
//        return language;
//    }

    /**
     * 切换横屏
     */
    public void changeLandscape() {
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); //横屏
    }

    /**
     * 切换竖屏
     */
    public void changePoptrait() {
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //竖屏
    }

}
